package com.gms.controller;

import com.gms.entity.user.User;
import com.gms.service.usermanager.UserService;
import com.gms.util.MD5Utils;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;

/**
 * 登录控制器
 *
 * @since2021/6/2 15:59
 */

@Controller
public class LoginController {

    @Autowired
    private UserService userService;


    @GetMapping("/login")
    public String Login(HttpSession session){
        session.removeAttribute("username");
        session.removeAttribute("permission");
        return "login";
    }

    @GetMapping("introduction")
    public String introduction(){
        return "introduction";
    }


    @GetMapping("/management")
    public String management(){
        return "management";
    }

    @RequestMapping("/toregister")
    public String toRegister(Model model){
        System.out.println("jingru");
        User user = new User();
        model.addAttribute("user",user);
        return "register";
    }

    //登录操作
    @RequestMapping("/loginUser")
    public String login(String aNumber, String passWord,String valide,Model model, HttpSession session){
        System.out.println(aNumber);
        String md5Password = MD5Utils.md5(passWord);
        User u1 = userService.login(aNumber,md5Password);
        String vrifyCode = (String) session.getAttribute("vrifyCode");
        if(!vrifyCode.equals(valide)){
            model.addAttribute("msg","验证码错误");
            return "login";
        }

        if (u1==null){
            model.addAttribute("msg","用户名或密码错误");
            return "login";
        }else{
            String permission = u1.getPermission();
            System.out.println(u1.getUserName());
            session.setAttribute("username",u1.getUserName());
            session.setAttribute("permission",permission);
            session.setAttribute("number",u1.getaNumber());
            session.setAttribute("user",u1);
            model.addAttribute("user",u1);

            if(u1.getPermission().equals("0")){
                return "redirect:/user/index";
            }
            return "management";
        }

    }


    @RequestMapping("registerUser")
    public String register(User user,Model model){
        User u2 = user;
        String password = MD5Utils.md5(u2.getPassWord());
        u2.setPassWord(password);
        u2.setPermission("0");
        u2.setRole("普通用户");
        u2.setState("正常");
        if (userService.checkForDuplication(u2.getaNumber())!=null){
            model.addAttribute("msg","该手机号已注册，请重新输入");
            model.addAttribute("user",user);
            return "register";
        }else
        {
            model.addAttribute("msg","注册成功");
            userService.register(u2);
            return "login";
        }

    }

    @Autowired
    private DefaultKaptcha captchaProducer;

    /**
     * 获取验证码
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @throws Exception
     */
    @RequestMapping("/defaultKaptcha")
    public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
            throws Exception {
        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            // 生产验证码字符串并保存到session中
            String createText = captchaProducer.createText();
            System.out.println(createText);
            httpServletRequest.getSession().setAttribute("vrifyCode", createText);
            // 使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = captchaProducer.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        // 定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }

}
